require 'View/UIBase/UIBase'

UIActivityDrawSP = UIBase.New(PanelResNames.UIActivityDrawSP)

local MustCountId = 5

function UIActivityDrawSP.Init(func, id)
    UIActivityDrawSP.activeId = id
    UIBase.Init(UIActivityDrawSP, func)
end

function UIActivityDrawSP:OnCreate()
    self.ctrlType = self:GetController("Type")
    self.btnClose = self:GetChild("Backbtn")
    self.btnHelp = self:GetChild("help")

    --召唤界面
    self.txtTime = self:GetChild("bannerText")
    self.txtTodayDrawTips = self:GetChild("tips")
    self.txtDrawTips = self:GetChild("DrawTips")
    self.btnDraw1 = self:GetChild("btndraw1")
    self.btnDraw5 = self:GetChild("btndraw5")
    self.btnTask = self:GetChild("BtnSign2")
    self.btnSwitch = self:GetChild("RewardBtn")
    self.listUpBox = self:GetChild("DrawBox1")
    self.listDownBox = self:GetChild("DrawBox2")
    self.fristMoney = self:GetChild("CoinLb1")
    self.secondMoney = self:GetChild("CoinLb")
    self.drawBoxList = {}
    self.redCtrl = self.btnTask:GetChild("UIRedDots"):GetController("c1")
    self.ctrlMask = self:GetController("mask")
    self.ctrlMask.selectedIndex = 0
    self.canClick = true
    for i= 1,5 do
        local drawBox = self:GetChild("DrawBox"..i)
        if drawBox then
            table.insert(self.drawBoxList, drawBox)
        end
    end
    --任务界面
    self.listTask = self:GetChild("TaskList")
    --奖励预览界面
    self.listReward = self:GetChild("ShowList")

    self:AddEvent()
    self:InitView()
    self:Refresh()
end

function UIActivityDrawSP:AddEvent()
    self:RegisterOnClick(self.btnDraw1,self.OnClickDraw1)
    self:RegisterOnClick(self.btnDraw5,self.OnClickDraw5)
    self:RegisterOnClick(self.btnSwitch,self.OnClickSwitch)
    self:RegisterOnClick(self.btnTask,self.OnClickTask)
    self:RegisterOnClick(self.btnClose,self.OnClickClose)
    self:RegisterOnClick(self.btnHelp,self.OnClickHelp)
    self:SetDynamicList(self.listTask ,self.TaskItemRender)
    self:SetDynamicList(self.listReward ,self.RewardReviewRender)
    self:RegisterEvent(Config.EventType.Fresh_Active,self.Refresh)
    self:RegisterEvent(Config.EventType.BlindBoxOpen,self.StartOpenBox)
end


function UIActivityDrawSP:InitView()
    self.tableData, self.srvData = logicMgr.ActiveManager.getActiveData(self.activeId)
    self.costItemId = tonumber(G.dataTable[tostring(self.tableData["f_ModelName"])][tostring(self.activeId)].f_DrawConsume[1]) or 1
    self.specialAwardItemId = tonumber(G.dataTable[tostring(self.tableData["f_ModelName"])][tostring(self.activeId)].f_ItemSP) or 1
    self.mustCount = G.dataTable["t_activitydrawsp"][tostring(MustCountId)]["f_Num2"] or 1
    self.ctrlType.selectedIndex = 0
    self.remainTime = self.srvData.endTime - HelperFunc.GetServerTime()
    for i = 1,5 do
        local aniWrap = self.drawBoxList[i]:GetChild("effect_yrjhd").wrapTarget
        Util.PlayAction(aniWrap, "idle1", true)
    end
    if self.remainTime > 0 then
        self.txtTime.text = string.format(getLanguage("Sys_ActivityTimeLeft"), HelperFunc.GetSurpTimeStr(self.remainTime))
    end
    self:TimeCall(self.UpdateActiveCountDown, 1000, -1)
end

function UIActivityDrawSP:UpdateActiveCountDown()
    if self.remainTime <= 0 then
        self.txtTime.text =  getLanguage("Sys_ActivityEnd")
        self:RemoveTimeCall(self.UpdateActiveCountDown)
    else
        self.txtTime.text = string.format(getLanguage("Sys_ActivityTimeLeft"), HelperFunc.GetSurpTimeStr(self.remainTime))
    end
    self.remainTime = self.remainTime - 1
end

function UIActivityDrawSP:Refresh()
    self.tableData, self.srvData = logicMgr.ActiveManager.getActiveData(self.activeId)
    if self.tableData and self.srvData then
        self.txtTodayDrawTips.text = string.format("今日召唤次数 %s/999999", self.srvData.todayCount)
        local haveCount = self.srvData.param.floorsProgress["5"] or 0
        self.txtDrawTips.text = string.format(string.format("再召唤%s次必得%s", self.mustCount - haveCount, getLanguage(G.dataTable["t_item"][tostring(self.specialAwardItemId)]["f_ItemName"])))
        self:RefreshTaskList()
        self:RefreshRewardReviewList()
        self:RefreshMoney(self.costItemId, 1)
        self:RefreshDrawBtn()
        if self.srvData.taskRedDots then
            self.redCtrl.selectedIndex = 2
        else
            self.redCtrl.selectedIndex = 0
        end
    end
end

function UIActivityDrawSP:RefreshDrawBtn()
    local haveNum = logicMgr.ItemManager.getCurrencyCountByModelId(self.costItemId)
    self.btnDraw1:GetChild("cost").url = "ui://ItemAtlas/" .. G.dataTable["t_item"][tostring(self.costItemId)].f_Icon
    self.btnDraw5:GetChild("cost").url = "ui://ItemAtlas/" .. G.dataTable["t_item"][tostring(self.costItemId)].f_Icon
    if haveNum >= 1 then
        self.btnDraw1:GetChild("num1").text = "[color=#FFFFFF]" .. 1 .. "[/color]"
        if haveNum >= 10 then
            self.btnDraw5:GetChild("num1").text = "[color=#FFFFFF]" .. 10 .. "[/color]"
        else
            self.btnDraw5:GetChild("num1").text = "[color=#FF0000]" .. 10 .. "[/color]"
        end
    else
        self.btnDraw1:GetChild("num1").text = "[color=#FF0000]" .. 1 .. "[/color]"
        self.btnDraw5:GetChild("num1").text = "[color=#FF0000]" .. 10 .. "[/color]"
    end
end

function UIActivityDrawSP:RefreshMoney(id1, id2)
    if id1 == nil then
        self.fristMoney.visible = false;
    else
        self.fristMoney.visible = true;
        local item1 = logicMgr.ItemManager.getItemConstDatabyModelId(id1);
        if item1 ~= nil then
            self.fristMoney:GetChild("icon").url = EnumConst.AtlasPath.ItemAtlas..item1.icon;
        end
        if tonumber(id1) == CurrencyEnum.MONEY then
            self.fristMoney:GetChild("title").text = getNumString(logicMgr.ItemManager.getCurrencyCountByModelId(tonumber(id1)));
        else
            self.fristMoney:GetChild("title").text = (logicMgr.ItemManager.getCurrencyCountByModelId(tonumber(id1)));
        end
    end
    if id2 == nil then
        self.secondMoney.visible = false;
    else
        self.secondMoney.visible = true;
        local item2 = logicMgr.ItemManager.getItemConstDatabyModelId(id2);
        if item2 ~= nil then
            self.secondMoney:GetChild("icon").url = EnumConst.AtlasPath.ItemAtlas..item2.icon;
        end
        if tonumber(id2) == CurrencyEnum.MONEY then
            self.secondMoney:GetChild("title").text = getNumString(logicMgr.ItemManager.getCurrencyCountByModelId(tonumber(id2)));
        else
            self.secondMoney:GetChild("title").text = (logicMgr.ItemManager.getCurrencyCountByModelId(tonumber(id2)));
        end
    end
end

function UIActivityDrawSP:RefreshTaskList()
    self.listTask.numItems = #self.srvData.taskCfgList
end

function UIActivityDrawSP:RefreshRewardReviewList()
    self.listReward.numItems = #self.srvData.previewRewardCfg
end

function UIActivityDrawSP:TaskItemRender(index, go)
    local cfgData = self.srvData.taskCfgList[index]
    local srvData = self.srvData.taskSrvMap[cfgData.f_ActTaskId]
    if cfgData then
        local txtTitle = go:GetChild("title")
        local btnGo = go:GetChild("btn_Go")
        local btnGet = go:GetChild("btn_Get")
        local listReward = go:GetChild("itemList")
        local ctrlState = go:GetController("status")
        txtTitle.text = string.format(getLanguage(cfgData.f_ActTaskDesc), 0)--getLanguage(cfgData.f_ActTaskDesc)
        logicMgr.CostManager.RefreshItemList(listReward, cfgData.f_Award)
        ctrlState.selectedIndex = 0
        if srvData then
            txtTitle.text = string.format(getLanguage(cfgData.f_ActTaskDesc), srvData.process)
            if srvData.process >= cfgData.f_Progress then
                if srvData.recvCount > 0 then
                    ctrlState.selectedIndex = 2
                else
                    ctrlState.selectedIndex = 1
                end
            end
        end
        btnGo.onClick:Clear()
        btnGo.onClick:Add(function()
            closeUI(PanelNames.UIActivity)
            closeUI(PanelNames.UIActivityDrawSP)
            closeUI(PanelNames.UIActivityList)
            showUI(PanelNames.UIHeadMenu)
            logicMgr.FuncOpenManager.jump(cfgData.f_Switchover)
        end)
        btnGet.onClick:Clear()
        btnGet.onClick:Add(function()
            ActivityHandler.sendReqActivityDrawRewardMessage({self.activeId, cfgData.f_ActTaskId})
        end)
    end
end

function UIActivityDrawSP:RewardReviewRender(index, go)
    local cfgData = self.srvData.previewRewardCfg[index]
    if cfgData then
        local txtTitle = go:GetChild("title")
        local imgBox = go:GetChild("Box")
        local listReward = go:GetChild("itemList")
        txtTitle.text = getLanguage(cfgData.f_ActTaskDesc)
        imgBox.url = cfgData.f_ActTaskPic
        logicMgr.CostManager.RefreshItemList(listReward, cfgData.f_Reward)
    end
end

function UIActivityDrawSP:StartOpenBox(giftData)
    for i = 1,5 do
        local imgBox = self.drawBoxList[i]:GetChild("Box")
        local aniWrap = self.drawBoxList[i]:GetChild("effect_yrjhd").wrapTarget
        if giftData and giftData[1] and giftData[1].accStarCards and giftData[1].accStarCards[i] then
            local itemInfo = dataTable.getDataTableByStringId("t_item", giftData[1].accStarCards[i].id)
            if itemInfo then
                if tonumber(giftData[1].accStarCards[i].id) == tonumber(self.specialAwardItemId) then
                    Util.PlayAction(aniWrap, "idle3", false)
                else
                    Util.PlayAction(aniWrap, "idle2", false)
                end
                utimer.delayCall(function()
                    imgBox.url = EnumConst.AtlasPath.ItemAtlas .. itemInfo.f_Icon
                end, 1000)
            end
        end
    end
    local itemList = self:MergeAllItems(giftData)
    self.revertTimer = utimer.delayCall(function()
        showUI(PanelNames.UICommonItemGet,nil,nil,3,itemList,function() self:RevertBox() end,nil,nil,nil,nil,false)
    end, 2000)
end

function UIActivityDrawSP:RevertBox()
    --local revertPath = G.dataTable[tostring(self.tableData.f_ModelName)][tostring(self.activeId)]["f_BgBox"]
    for i = 1,5 do
        local imgBox = self.drawBoxList[i]:GetChild("Box")
        local aniWrap = self.drawBoxList[i]:GetChild("effect_yrjhd").wrapTarget
        imgBox.url = ""
        Util.PlayAction(aniWrap, "idle1", true)
    end
end

--function UIActivityDrawSP:GetCurCount(index,table)
--    return tab
--end

function UIActivityDrawSP:OnClickDraw1()
    if self.canClick then
        local haveNum = logicMgr.ItemManager.getCurrencyCountByModelId(self.costItemId)
        if haveNum >= 1 then
            ActivityHandler.ReqLotteryDrawSp(self.activeId, 1)
            self.canClick = false
            utimer.delayCall(function() self.canClick = true end, 2500)
        else
            UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"), getLanguage(G.dataTable["t_item"][tostring(self.costItemId)].f_ItemName)))
        end
    end
end

function UIActivityDrawSP:OnClickDraw5()
    if self.canClick then
        local haveNum = logicMgr.ItemManager.getCurrencyCountByModelId(self.costItemId)
        if haveNum >= 10 then
            ActivityHandler.ReqLotteryDrawSp(self.activeId, 10)
            self.canClick = false
            utimer.delayCall(function() self.canClick = true end, 2500)
        else
            UISysTips.AddMsg(string.format(getLanguage("Character_Tips19"), getLanguage(G.dataTable["t_item"][tostring(self.costItemId)].f_ItemName)))
        end
    end
end

function UIActivityDrawSP:OnClickSwitch()
    if self.ctrlType.selectedIndex == 0 then
        self.ctrlType.selectedIndex = 2
    elseif self.ctrlType.selectedIndex == 2 then
        self.ctrlType.selectedIndex = 0
    end
end

function UIActivityDrawSP:OnClickTask()
    self.ctrlType.selectedIndex = 1
end

function UIActivityDrawSP:OnClickHelp()
    local txts = {}
    txts["title"] = tostring(G.dataTable[tostring(self.tableData["f_ModelName"])][tostring(self.activeId)].f_ExplainTitle)
    txts["des"] = tostring(G.dataTable[tostring(self.tableData["f_ModelName"])][tostring(self.activeId)].f_ExplainText)
    showUI(PanelNames.CommonTips, txts)
end

function UIActivityDrawSP:MergeAllItems(itemContent)
    if itemContent then
        local itemList = {}
        local mergeList = {}
        for k,v in pairs(itemContent) do
            for m,n in pairs(v.itemList) do
                table.insert(itemList, n)
            end
        end
        for k,v in pairs(itemList) do
            local isMerge = false
            for m,n in pairs(mergeList) do
                if v.itemModelId == n.itemModelId then
                    n.num = tonumber(tostring(v.num)) + tonumber(tostring(n.num))
                    isMerge = true
                end
            end
            if not isMerge then
                table.insert(mergeList, v)
            end
        end
        return mergeList
    end
end

function UIActivityDrawSP:OnClickClose()
    if self.canClick then
        if self.ctrlType.selectedIndex == 1 then
            self.ctrlType.selectedIndex = 0
        elseif self.ctrlType.selectedIndex == 2 then
            self.ctrlType.selectedIndex = 0
        else
            if self.revertTimer then
                utimer.remove(self.revertTimer)
                self.revertTimer = nil
            end
            closeUI(PanelNames.UIActivityDrawSP)
        end
    end
end

return UIActivityDrawSP